import os
import cv2
import numpy as np
import pyautogui
import threading
import time
from datetime import datetime
from typing import Optional
from .logger import logger
from .config import config

# 全局变量
_recording = False
_paused = False
_output_path = None
_thread = None
_writer = None

def start_recording(output_dir: str) -> bool:
    """开始录制屏幕"""
    global _recording, _paused, _output_path, _thread, _writer
    
    try:
        if _recording:
            logger.warning("录制已在进行中")
            return False
            
        # 确保输出目录存在
        os.makedirs(output_dir, exist_ok=True)
        
        # 生成输出文件路径
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        _output_path = os.path.join(output_dir, f"recording_{timestamp}.mp4")
        
        # 获取屏幕尺寸
        screen_width, screen_height = pyautogui.size()
        
        # 配置视频编码器
        fourcc = cv2.VideoWriter_fourcc(*'mp4v')
        fps = config.get('video.fps', 30)
        
        # 创建视频写入器
        _writer = cv2.VideoWriter(_output_path, fourcc, fps, (screen_width, screen_height))
        
        # 设置录制状态
        _recording = True
        _paused = False
        
        # 启动录制线程
        _thread = threading.Thread(target=_record_screen)
        _thread.start()
        
        logger.info(f"开始录制屏幕: {_output_path}")
        return True
        
    except Exception as e:
        logger.error(f"开始录制失败: {str(e)}")
        _cleanup()
        return False

def pause_recording() -> bool:
    """暂停录制"""
    global _paused
    
    try:
        if not _recording:
            logger.warning("没有正在进行的录制")
            return False
            
        _paused = True
        logger.info("录制已暂停")
        return True
        
    except Exception as e:
        logger.error(f"暂停录制失败: {str(e)}")
        return False

def resume_recording() -> bool:
    """恢复录制"""
    global _paused
    
    try:
        if not _recording:
            logger.warning("没有正在进行的录制")
            return False
            
        _paused = False
        logger.info("录制已恢复")
        return True
        
    except Exception as e:
        logger.error(f"恢复录制失败: {str(e)}")
        return False

def stop_recording() -> Optional[str]:
    """停止录制"""
    global _recording, _paused, _output_path, _thread, _writer
    
    try:
        if not _recording:
            logger.warning("没有正在进行的录制")
            return None
            
        # 停止录制
        _recording = False
        _paused = False
        
        # 等待录制线程结束
        if _thread and _thread.is_alive():
            _thread.join()
        
        # 释放资源
        if _writer:
            _writer.release()
        
        output_path = _output_path
        _cleanup()
        
        logger.info(f"录制已停止: {output_path}")
        return output_path
        
    except Exception as e:
        logger.error(f"停止录制失败: {str(e)}")
        _cleanup()
        return None

def _record_screen():
    """屏幕录制线程"""
    global _recording, _paused, _writer
    
    try:
        while _recording:
            if not _paused:
                # 截取屏幕
                screenshot = pyautogui.screenshot()
                
                # 转换为OpenCV格式
                frame = cv2.cvtColor(np.array(screenshot), cv2.COLOR_RGB2BGR)
                
                # 写入帧
                _writer.write(frame)
                
            # 控制帧率
            time.sleep(1/config.get('video.fps', 30))
            
    except Exception as e:
        logger.error(f"录制线程异常: {str(e)}")
        _cleanup()

def _cleanup():
    """清理资源"""
    global _recording, _paused, _output_path, _thread, _writer
    
    _recording = False
    _paused = False
    _output_path = None
    _thread = None
    
    if _writer:
        try:
            _writer.release()
        except:
            pass
        _writer = None

def is_recording() -> bool:
    """检查是否正在录制"""
    return _recording

def is_paused() -> bool:
    """检查是否已暂停"""
    return _paused

def get_output_path() -> Optional[str]:
    """获取当前录制文件路径"""
    return _output_path
